package com.steven.ourcontest.chat.widget

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import androidx.constraintlayout.widget.ConstraintLayout
import com.steven.ourcontest.R
import kotlinx.android.synthetic.main.view_chat_tab.view.*

class ChatTabBar(context: Context, attrs: AttributeSet) : ConstraintLayout(context, attrs) {

    companion object {
        const val TAB_MESSAGE = 0
        const val TAB_FRIENDS = 1
    }

    var currentTab = -1
    var selectListener: OnSelectListener? = null

    init {
        LayoutInflater.from(context).inflate(R.layout.view_chat_tab, this, true)

        iv_message?.setImageResource(R.drawable.ic_tab_message_selected)
        iv_friends?.setImageResource(R.drawable.ic_tab_friends_unselected)
        setCurrentItem(TAB_MESSAGE)

        ll_message?.setOnClickListener {
            setCurrentItem(TAB_MESSAGE)
        }
        ll_friends?.setOnClickListener {
            setCurrentItem(TAB_FRIENDS)
        }
    }

    fun setCurrentItem(index: Int) {
        if (currentTab == index) {
            return
        }
        if (selectListener?.onSelected(currentTab, index) == false) {
            return
        }
        when (currentTab) {
            TAB_MESSAGE -> {
                iv_message?.setImageResource(R.drawable.ic_tab_message_unselected)
            }
            TAB_FRIENDS -> {
                iv_friends?.setImageResource(R.drawable.ic_tab_friends_unselected)
            }
        }
        when (index) {
            TAB_MESSAGE -> {
                iv_message?.setImageResource(R.drawable.ic_tab_message_selected)
            }
            TAB_FRIENDS -> {
                iv_friends?.setImageResource(R.drawable.ic_tab_friends_selected)
            }
        }
        currentTab = index
    }

    fun slideItem(index: Int){
        if (currentTab == index) {
            return
        }
        when (currentTab) {
            TAB_MESSAGE -> {
                iv_message?.setImageResource(R.drawable.ic_tab_message_unselected)
            }
            TAB_FRIENDS -> {
                iv_friends?.setImageResource(R.drawable.ic_tab_friends_unselected)
            }
        }
        when (index) {
            TAB_MESSAGE -> {
                iv_message?.setImageResource(R.drawable.ic_tab_message_selected)
            }
            TAB_FRIENDS -> {
                iv_friends?.setImageResource(R.drawable.ic_tab_friends_selected)
            }
        }
        currentTab = index
    }
}

interface OnSelectListener {
    fun onSelected(current: Int, index: Int): Boolean
}